<?php

/**
 * SocialEngine
 *
 * @category   Application_Extensions
 * @package    Sitereview
 * @copyright  Copyright 2012-2013 BigStep Technologies Pvt. Ltd.
 * @license    http://www.socialengineaddons.com/license/
 * @version    $Id: Create.php 6590 2013-04-01 00:00:00Z SocialEngineAddOns $
 * @author     SocialEngineAddOns
 */
class Sitereview_Form_Create extends Engine_Form {

  public $_error = array();
  protected $_defaultProfileId;

  public function getDefaultProfileId() {
    return $this->_defaultProfileId;
  }

  public function setDefaultProfileId($default_profile_id) {
    $this->_defaultProfileId = $default_profile_id;
    return $this;
  }

  public function init() {

    //GET LISTING TYPE ID
    $listingtype_id = Zend_Controller_Front::getInstance()->getRequest()->getParam('listingtype_id', null);

    $listingtypeArray = Zend_Registry::get('listingtypeArray' . $listingtype_id);
    $listingTypeInfo = Zend_Registry::isRegistered('sitereviewListingTypeInfo') ? Zend_Registry::get('sitereviewListingTypeInfo') : null;
    $listing_singular_uc = ucfirst($listingtypeArray->title_singular);
    $listing_singular_lc = strtolower($listingtypeArray->title_singular);
    $listing_plural_lc = strtolower($listingtypeArray->title_plural);
    $listing_plural_uc = ucfirst($listingtypeArray->title_plural);

    $listing_singular_upper = strtoupper($listingtypeArray->title_singular);
    $note = '';
    $settings = Engine_Api::_()->getApi('settings', 'core');
    $reviewApi = Engine_Api::_()->sitereview();
    $expirySettings = $reviewApi->expirySettings($listingtype_id);
    if ($expirySettings == 2) {
      $translate = Zend_Registry::get('Zend_Translate');
      $duration = $listingtypeArray->admin_expiry_duration;
      $typeStr = $translate->translate(array($duration[1], $duration[1] . 's', $duration[0]));
      $note = sprintf($translate->translate('Note: your ' . $listing_singular_lc . ' will be expired in %1$s %2$s after an approval or it may be changed by admin.'), $duration[0], $typeStr);
    }

    $this->setTitle(sprintf(Zend_Registry::get('Zend_Translate')->_("Post New $listing_singular_uc")))
            ->setDescription(sprintf(Zend_Registry::get('Zend_Translate')->_("Compose your new $listing_singular_lc below, then click 'Submit' to publish the $listing_singular_lc.")))
            ->setAction(Zend_Controller_Front::getInstance()->getRouter()->assemble(array()))
            ->setAttrib('name', 'sitereviews_create');

    $this->addElement('Text', 'title', array(
        'label' => "$listing_singular_uc Title",
        'allowEmpty' => false,
        'required' => true,
        'filters' => array(
            'StripTags',
            new Engine_Filter_Censor(),
        //new Engine_Filter_StringLength(array('max' => '63')),
            )));

    $user = Engine_Api::_()->user()->getViewer();
    $user_level = Engine_Api::_()->user()->getViewer()->level_id;

    $this->addElement('Text', 'tags', array(
        'label' => $listing_singular_upper . '_TAG_(Keywords)',
        'autocomplete' => 'off',
        'description' => Zend_Registry::get('Zend_Translate')->_('SEPARATE_' . $listing_singular_upper . '_TAGS_WITH_COMMAS'),
        'filters' => array(
            new Engine_Filter_Censor(),
        ),
    ));
    $this->tags->getDecorator("Description")->setOption("placement", "append");
    
    $defaultProfileId = "0_0_" . $this->getDefaultProfileId();

    if (!$this->_item || (isset($this->_item->category_id) && empty($this->_item->category_id)) || ($this->_item && $listingtypeArray->category_edit)) {
      $categories = Engine_Api::_()->getDbTable('categories', 'sitereview')->getCategories(null, 0, $listingtype_id, 0, 1);
      if (count($categories) != 0) {
        $categories_prepared[0] = "";
        foreach ($categories as $category) {
          $categories_prepared[$category->category_id] = $category->category_name;
        }

        $this->addElement('Select', 'category_id', array(
            'label' => 'Category',
            'allowEmpty' => false,
            'required' => true,
            'multiOptions' => $categories_prepared,
            'onchange' => "showFields($(this).value, 1); subcategories(this.value, '', '');",
        ));

        $this->addElement('Select', 'subcategory_id', array(
            'RegisterInArrayValidator' => false,
            'allowEmpty' => true,
            'required' => false,
        ));

        $this->addElement('Select', 'subsubcategory_id', array(
            'RegisterInArrayValidator' => false,
            'allowEmpty' => true,
            'required' => false,
        ));

        $this->addDisplayGroup(array(
            'subcategory_id',
            'subsubcategory_id',
                ), 'Select', array(
            'decorators' => array(array('ViewScript', array(
                        'viewScript' => 'application/modules/Sitereview/views/scripts/_formSubcategory.tpl',
                        'class' => 'form element')))
        ));
      }
    }    

    $allowOverview = Engine_Api::_()->authorization()->getPermission($user->level_id, 'sitereview_listing', "overview_listtype_$listingtypeArray->listingtype_id");
    $allowEdit = Engine_Api::_()->authorization()->getPermission($user->level_id, 'sitereview_listing', "edit_listtype_$listingtypeArray->listingtype_id");

    if ($listingtypeArray->overview && $listingtypeArray->overview_creation && $allowOverview && $allowEdit && !$this->_item) {
      $description = 'Short Description';
    } else {
      $description = 'Description';
    }
    
    if ($listingtypeArray->body_allow) {

			if (!empty($listingtypeArray->body_required)) {

				$this->addElement('textarea', 'body', array(
						'label' => $description,
						'required' => true,
						'allowEmpty' => false,
						'attribs' => array('rows' => 24, 'cols' => 180, 'style' => 'width:300px; max-width:400px;height:120px;'),
						'filters' => array(
								'StripTags',
								//new Engine_Filter_HtmlSpecialChars(),
								new Engine_Filter_EnableLinks(),
								new Engine_Filter_Censor(),
						),
				));
			} else {

				$this->addElement('textarea', 'body', array(
						'label' => 'Description',
						'attribs' => array('rows' => 24, 'cols' => 180, 'style' => 'width:300px; max-width:400px;height:120px;'),
						'filters' => array(
								'StripTags',
								//new Engine_Filter_HtmlSpecialChars(),
								new Engine_Filter_EnableLinks(),
								new Engine_Filter_Censor(),
						),
				));
			}

    }

    if ($listingtypeArray->overview && $listingtypeArray->overview_creation && $allowOverview && $allowEdit && !$this->_item) {
      $this->addElement('Textarea', 'overview', array(
          'label' => 'DASHBOARD_' . $listing_singular_upper . '_OVERVIEW',
          'filters' => array(new Engine_Filter_Censor()),
      ));
    }

    $allowed_upload = Engine_Api::_()->authorization()->getPermission($user_level, 'sitereview_listing', "photo_listtype_$listingtype_id");
    if ($allowed_upload && ($listingtypeArray->photo_type == 'listing')) {
      $this->addElement('File', 'photo', array(
          'label' => 'Main Photo'
      ));
      $this->photo->addValidator('Extension', false, 'jpg,jpeg,png,gif');
    }

    if ($listingtypeArray->location) {
      $this->addElement('Text', 'location', array(
          'label' => 'Location',
          'description' => 'Eg: Fairview Park, Berkeley, CA',
          'filters' => array(
              'StripTags',
              new Engine_Filter_Censor(),
              )));
      $this->location->getDecorator('Description')->setOption('placement', 'append');
    }

    if ($listingtypeArray->price) {
      $localeObject = Zend_Registry::get('Locale');
      $currencyCode = Engine_Api::_()->getApi('settings', 'core')->getSetting('payment.currency', 'USD');
      $currencyName = Zend_Locale_Data::getContent($localeObject, 'nametocurrency', $currencyCode);
      $this->addElement('Text', 'price', array(
          'label' => sprintf(Zend_Registry::get('Zend_Translate')->_('Price (%s)'), $currencyName),
          'filters' => array(
              'StripTags',
              new Engine_Filter_Censor(),
              )));
    }

    if (!$this->_item) {
      $customFields = new Sitereview_Form_Custom_Standard(array(
                  'item' => 'sitereview_listing',
                  'decorators' => array(
                      'FormElements'
                      )));
    } else {
      $customFields = new Sitereview_Form_Custom_Standard(array(
                  'item' => $this->getItem(),
                  'decorators' => array(
                      'FormElements'
                      )));
    }

    $customFields->removeElement('submit');
    if ($customFields->getElement($defaultProfileId)) {
      $customFields->getElement($defaultProfileId)
              ->clearValidators()
              ->setRequired(false)
              ->setAllowEmpty(true);
    }

    $this->addSubForms(array(
        'fields' => $customFields
    ));

    $availableLabels = array(
        'everyone' => 'Everyone',
        'registered' => 'All Registered Members',
        'owner_network' => 'Friends and Networks',
        'owner_member_member' => 'Friends of Friends',
        'owner_member' => 'Friends Only',
        'owner' => 'Just Me',
    );

    $view_options = (array) Engine_Api::_()->authorization()->getAdapter('levels')->getAllowed('sitereview_listing', $user, "auth_view_listtype_$listingtype_id");
    $view_options = array_intersect_key($availableLabels, array_flip($view_options));

    if (count($view_options) >= 1) {
      $this->addElement('Select', 'auth_view', array(
          'label' => 'View Privacy',
          'description' => Zend_Registry::get('Zend_Translate')->_("Who may see this $listing_singular_lc?"),
          'multiOptions' => $view_options,
          'value' => key($view_options),
      ));
      $this->auth_view->getDecorator('Description')->setOption('placement', 'append');
    } else {
      $this->addElement('Hidden', 'auth_view', array(
          'value' => "everyone"
      ));
    }

    $comment_options = (array) Engine_Api::_()->authorization()->getAdapter('levels')->getAllowed('sitereview_listing', $user, "auth_comment_listtype_$listingtype_id");
    $comment_options = array_intersect_key($availableLabels, array_flip($comment_options));

    if (count($comment_options) >= 1) {
      $this->addElement('Select', 'auth_comment', array(
          'label' => 'Comment Privacy',
          'description' => Zend_Registry::get('Zend_Translate')->_("Who may comment on this $listing_singular_lc?"),
          'multiOptions' => $comment_options,
          'value' => key($comment_options),
      ));
      $this->auth_comment->getDecorator('Description')->setOption('placement', 'append');
    } else {
      $this->addElement('Hidden', 'auth_comment', array('value' => "everyone"));
    }

    $availableLabels = array(
        'registered' => 'All Registered Members',
        'owner_network' => 'Friends and Networks',
        'owner_member_member' => 'Friends of Friends',
        'owner_member' => 'Friends Only',
        'owner' => 'Just Me',
    );
    $photo_options = (array) Engine_Api::_()->authorization()->getAdapter('levels')->getAllowed('sitereview_listing', $user, "auth_photo_listtype_$listingtype_id");
    $photo_options = array_intersect_key($availableLabels, array_flip($photo_options));

    if (count($photo_options) >= 1) {
      $this->addElement('Select', 'auth_photo', array(
          'label' => 'Photo Privacy',
          'description' => Zend_Registry::get('Zend_Translate')->_("Who may upload photos for this $listing_singular_lc?"),
          'multiOptions' => $photo_options,
          'value' => key($photo_options),
      ));
      $this->auth_photo->getDecorator('Description')->setOption('placement', 'append');
    } else {
      $this->addElement('Hidden', 'auth_photo', array(
          'value' => 'registered',
      ));
    }

    $videoEnable = Engine_Api::_()->sitereview()->enableVideoPlugin();
    if ($videoEnable) {

      $video_options = (array) Engine_Api::_()->authorization()->getAdapter('levels')->getAllowed('sitereview_listing', $user, "auth_video_listtype_$listingtype_id");
      $video_options = array_intersect_key($availableLabels, array_flip($video_options));

      if (count($video_options) >= 1) {
        $this->addElement('Select', 'auth_video', array(
            'label' => 'Video Privacy',
            'description' => Zend_Registry::get('Zend_Translate')->_("Who may create videos for this $listing_singular_lc?"),
            'multiOptions' => $video_options,
            'value' => key($video_options),
        ));
        $this->auth_video->getDecorator('Description')->setOption('placement', 'append');
      } else {
        $this->addElement('Hidden', 'auth_video', array(
            'value' => 'registered',
        ));
      }
    }

    //NETWORK BASE PAGE VIEW PRIVACY
    if (Engine_Api::_()->sitereview()->listBaseNetworkEnable()) {
      // Make Network List
      $table = Engine_Api::_()->getDbtable('networks', 'network');
      $select = $table->select()
              ->from($table->info('name'), array('network_id', 'title'))
              ->order('title');
      $result = $table->fetchAll($select);

      $networksOptions = array('0' => 'Everyone');
      foreach ($result as $value) {
        $networksOptions[$value->network_id] = $value->title;
      }

      if (count($networksOptions) > 0) {
        $this->addElement('Multiselect', 'networks_privacy', array(
            'label' => 'Networks Selection',
            'description' => Zend_Registry::get('Zend_Translate')->_("Select the networks, members of which should be able to see your $listing_singular_lc. (Press Ctrl and click to select multiple networks. You can also choose to make your $listing_singular_lc viewable to everyone.)"),
//            'attribs' => array('style' => 'max-height:150px; '),
            'multiOptions' => $networksOptions,
            'value' => array(0)
        ));
      } else {
        
      }
    }

    $this->addElement('Radio', 'end_date_enable', array(
        'label' => 'End Date',
        'multiOptions' => array("0" => "No end date.", "1" => "End $listing_singular_lc on a specific date. (Please select date by clicking on the calendar icon below.)"),
        'description' => "When should this $listing_singular_lc end?",
        'value' => 0,
        'onclick' => "updateTextFields(this)",
    ));
    // End time
    $end = new Engine_Form_Element_CalendarDateTime('end_date');
    $end->setAllowEmpty(false);
    $date = (string) date('Y-m-d');
    $end->setValue($date . ' 00:00:00');
    $this->addElement($end);

    $this->addElement('Select', 'draft', array(
        'label' => 'Status',
        'multiOptions' => array("0" => "Published", "1" => "Saved As Draft"),
        'description' => 'If this '.$listing_singular_lc.' is published, it cannot be switched back to draft mode.',
        'onchange' => 'checkDraft();'
    ));
    $this->draft->getDecorator('Description')->setOption('placement', 'append');
    
    $tempValue = !empty($listingTypeInfo)? $listingTypeInfo: false;
    $this->addElement('Hidden', 'listing_info', array(
          'value' => $tempValue
      ));

    $this->addElement('Checkbox', 'search', array(
        //'label' => "Show this $listing_singular_lc in search results",
        'label' => "Show this $listing_singular_lc on browse page and in various blocks.",
        'value' => 1,
    ));

    $this->addElement('Button', 'execute', array(
        'label' => 'Submit',
        'type' => 'submit',
        'ignore' => true,
        'decorators' => array(
            'ViewHelper',
        ),
    ));

    $this->addElement('Cancel', 'cancel', array(
        'label' => 'cancel',
        'link' => true,
        'prependText' => ' or ',
        'href' => Zend_Controller_Front::getInstance()->getRouter()->assemble(array('action' => 'manage'), "sitereview_general_listtype_$listingtype_id", true),
        'decorators' => array(
            'ViewHelper',
        ),
    ));

    $this->addDisplayGroup(array(
        'execute',
        'cancel',
            ), 'buttons', array(
        'decorators' => array(
            'FormElements',
            'DivDivDivWrapper'
        ),
    ));
  }

}